extends Node


var deck=load("res://Model/Pile.gd").new()
var discard_pile=load("res://Model/Pile.gd").new()
var hand=load("res://Model/Pile.gd").new()
var consume_pile=load("res://Model/Pile.gd").new()
var energy=3 setget setEnergy
var energyBase=3 #每回合的能量
var drawNumber=5 #每回合抽牌数
var isReboot=false #用来记录这个回合有没有reboot，一回合只能reboot一次

onready var handView=$handView
func setEnergy(value):
	energy=value
	$"数据面版/能量数".text=String(energy)
	pass


func _ready():
	#注册全局变量
	Global.CardSystem=self
	#连接
	deck.connect("sizeChange",self,"onDeckSizeChange")
	discard_pile.connect("sizeChange",self,"onDiscardPileSizeChange")
	consume_pile.connect("sizeChange",self,"onConsumePileSizeChange")
	
func start(cards,energyBase_,drawNumber_):
	#初始化数据
	energyBase=energyBase_
	#卡组
	deck.replaceCards(cards)
	deck.shuffle()
	drawNumber=drawNumber_

func turnBegin():
	
	isReboot=false
	setEnergy(energyBase)
	multiDraw(drawNumber)
	$handView.setState($handView.state_idle)
	

#抽牌
func draw():
	if deck.size==0:
		if discard_pile.size>0:
			if !isReboot:
				reboot()
				isReboot=true
			else:
				return
		else:
			return
	var card=deck.pop_front()
	hand.append(card)
	$handView.append(card)

#牌抽完后重置卡牌
func reboot():
	deck.replaceCards(discard_pile.getCards())
	deck.shuffle()
	discard_pile.clear()
	pass
func useCard(card,target=null):
	if energy<card.cost:
		#使用失败
		return 0
	self.energy-=card.cost 
	discard(card)
	#触发卡牌使用效果
	#触发卡牌的效果
	if card.useType<=2:  #指向型
		var dh=[0]
		card.useFunc.call_func(dh,card.user,target)
		Global.Battle.appendDonghua(dh)
	else:   #非指向型
		var dh=[0]
		card.useFunc.call_func(dh,card.user)
		Global.Battle.appendDonghua(dh)
	#使用成功
	
	return 1
#随机丢弃卡牌
func discardRandom():
	if hand.size>0:
		var i=rand_range(0,hand.size)
		var card=hand.cards[i]
		discard(card)
#弃牌,手牌进入弃牌堆
func discard(card):
	hand.erase(card)
	discard_pile.append(card)
	#handView里面的牌进入弃牌堆
	handView.discard(card)
	pass
func discardAll():
	for i in range(hand.size-1,-1,-1):
		discard(hand.cards[i])
func multiDraw(number):
	for i in range(number):
		draw()
#除外
func except(card):
	if hand.cards.has(card):
		hand.erase(card)
		handView.discard(card)
	elif deck.cards.has(card):
		deck.erase(card)
	elif discard_pile.cards.has(card):
		discard_pile.erase(card)
	consume_pile.append(card)
	pass
#除外一个chess的所有卡牌 在chess死亡后使用
func exceptChessCard(chess):
	for card in chess.cards:
		except(card)
	pass
func _physics_process(delta):
	if Input.is_action_just_pressed("ui_accept"):
		self.energy+=1
		draw()
func playerTurnEnd():
	$handView.setState($handView.state_disable)
	discardAll()
	pass

func onDeckSizeChange(size_):
	$"数据面版/抽牌堆数".text=String(size_)
	pass
func onDiscardPileSizeChange(size_):
	$"数据面版/弃牌堆数".text=String(size_)
	pass
func onConsumePileSizeChange(size_):
	$"数据面版/除外数".text=String(size_)